import { authInstance, aiInstance, voiceInstance, ttsInstance } from './request';

// ==================== 类型定义 ====================

// 登录相关类型
export interface LoginRequest {
  account: string;
  password: string;
}

export interface LoginResponse {
  username: string;
  role: number;
  userId: number;
  token: string;
}

// 语音识别相关类型
export interface AsrRequest {
  accessToken: string;
  cuid: string;
  devPid?: number;
  format: 'wav' | 'pcm';
  sampleRate?: number;
  channel?: 1;
  speechBase64: string;
  rawBytesLength: number;
}

export interface AsrSuccess {
  text: string;
  raw: unknown;
}

export interface AsrError {
  code: number;
  message: string;
  raw?: unknown;
}

// AI对话相关类型
export interface DeepseekMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

export interface DeepseekRequest {
  apiKey: string;
  model?: string;
  messages: DeepseekMessage[];
  appId?: string;
  appSecret?: string;
}

// TTS相关类型
export interface TtsOptions {
  text: string;
  appKey: string;
  appSecret: string;
  voiceName?: string;
  format?: 'mp3' | 'wav';
  speed?: string;
  volume?: string;
  pitch?: string;
}

// ==================== 认证服务 ====================

export const authAPI = {
  // 用户登录
  login: async (data: LoginRequest): Promise<LoginResponse> => {
    const response = await authInstance.post('/login', data);
    return response.data;
  },

  // 用户登出
  logout: async (): Promise<void> => {
    await authInstance.post('/logout');
  },

  // 获取用户信息
  getUserInfo: async (): Promise<LoginResponse> => {
    const response = await authInstance.get('/user/info');
    return response.data;
  },
};

// ==================== AI服务 ====================

export const aiAPI = {
  // DeepSeek对话
  chat: async (params: DeepseekRequest): Promise<string> => {
    const body = {
      model: params.model ?? 'deepseek-r1-250120',
      messages: params.messages,
      stream: false,
    };

    const response = await aiInstance.post('', body, {
      headers: {
        'Authorization': `Bearer ${params.apiKey}`,
        ...(params.appId ? { 'X-App-Id': params.appId } : {}),
        ...(params.appSecret ? { 'X-App-Secret': params.appSecret } : {}),
      },
    });

    return response.data?.choices?.[0]?.message?.content ?? '';
  },
};

// ==================== 语音服务 ====================

export const voiceAPI = {
  // 语音识别
  recognize: async (req: AsrRequest): Promise<AsrSuccess> => {
    const body = {
      format: req.format,
      rate: req.sampleRate ?? 16000,
      channel: req.channel ?? 1,
      cuid: req.cuid,
      token: req.accessToken,
      dev_pid: req.devPid ?? 1537,
      lan: 'zh',
      len: req.rawBytesLength,
      speech: req.speechBase64,
    };

    const response = await voiceInstance.post('', body);

    if (response.data.err_no !== 0) {
      const message = typeof response.data.err_msg === 'string' ? response.data.err_msg : 'asr error';
      throw { code: response.data.err_no, message, raw: response.data } as AsrError;
    }

    const text: string = Array.isArray(response.data.result) && response.data.result.length > 0 
      ? response.data.result[0] 
      : '';
    
    return { text, raw: response.data } as AsrSuccess;
  },
};

// ==================== TTS服务 ====================

export const ttsAPI = {
  // 文字转语音
  synthesize: async (opts: TtsOptions): Promise<Blob> => {
    // 生成签名
    const salt = crypto.randomUUID();
    const curtime = Math.floor(Date.now() / 1000).toString();
    const inputRaw = opts.text;
    const inputEncoded = encodeURIComponent(inputRaw);
    
    // 计算签名
    const signStr = opts.appKey + inputEncoded + salt + curtime + opts.appSecret;
    const sign = await sha256Hex(signStr);

    // 构建表单数据
    const form = new URLSearchParams();
    form.set('appKey', opts.appKey);
    form.set('salt', salt);
    form.set('signType', 'v3');
    form.set('curtime', curtime);
    form.set('sign', sign);
    form.set('input', inputRaw);
    form.set('format', opts.format ?? 'mp3');
    if (opts.voiceName) form.set('voiceName', opts.voiceName);
    if (opts.speed) form.set('speed', opts.speed);
    if (opts.volume) form.set('volume', opts.volume);
    if (opts.pitch) form.set('pitch', opts.pitch);

    const response = await ttsInstance.post('', form.toString());

    const contentType = response.headers['content-type'] || '';
    if (contentType.includes('application/json')) {
      const json = response.data;
      if (json && json.errorCode && json.errorCode !== '0') {
        const err = new Error(`TTS error: ${JSON.stringify(json)}`) as Error & { code?: string; requestId?: string };
        err.code = json.errorCode;
        err.requestId = json.requestId;
        throw err;
      }
      if (json && json.audioBase64) {
        const bytes = Uint8Array.from(atob(json.audioBase64), c => c.charCodeAt(0));
        return new Blob([bytes], { type: 'audio/mp3' });
      }
      throw new Error(`TTS error: unexpected JSON ${JSON.stringify(json)}`);
    }
    
    return new Blob([response.data], { type: 'audio/mp3' });
  },
};

// ==================== 工具函数 ====================

// SHA256哈希函数
function sha256Hex(input: string): Promise<string> {
  const enc = new TextEncoder();
  const data = enc.encode(input);
  return crypto.subtle.digest('SHA-256', data).then(buf =>
    Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('')
  );
}
